<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>手写 apply 方法</title>
</head>

<body>

  <script>
    /**
     * 手写 apply 方法
     * 1. 定义 myApply 方法
     * 2. 设置 this 并调用原函数
     * 3. 接收参数并返回结果
     * */

    Function.prototype.myApply = function (thisArg, args) {
      // 2. 设置 this 并调用原函数
      const key = Symbol('key')
      thisArg[key] = this
      const res = thisArg[key](...args)
      delete thisArg[key]
      return res
    }



    //  测试代码
    const person = {
      name: 'Ali'
    }
    function func(numA, numB) {
      console.log(this)
      console.log(numA, numB)
      return numA + numB
    }
    const res = func.myApply(person, [2, 8])
    console.log('返回值为', res)

  </script>
</body>

</html>